package cn.line5.seam.webapp;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.line5.seam.cache.UploadConfigCache;
import cn.line5.seam.contexts.UploadContext;

/**
 * <h1>多文件上传实现类</h1>
 * 
 * @author Liu,Xiaojun
 * @since JDK1.6
 */
public class UploadFiles {

	private HttpServletRequest request;

	private String uploadPath;

	private String fileType;

	/**
	 * 构造方法，设置HttpServletRequest对象、上传路径和限制文件类型。
	 */
	public UploadFiles(HttpServletRequest request, String uploadPath,
			String fileType) {
		this.request = request;
		this.uploadPath = uploadPath == null ? UploadConfigCache.uploadPath
				: uploadPath;
		this.fileType = fileType == null ? "" : fileType.toLowerCase();
	}

	/**
	 * 上传文件
	 * 
	 * @return 上传结果
	 */
	public UploadResult upload() {
		init();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(UploadConfigCache.sizeThreshold);
		factory.setRepository(new File(request.getSession().getServletContext()
				.getRealPath(UploadConfigCache.uploadTempPath)));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(UploadConfigCache.fileSizeMax);
		upload.setSizeMax(UploadConfigCache.sizeMax);
		upload.setHeaderEncoding(UploadConfigCache.encoding);
		UploadResult result = new UploadResult();
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> items = upload.parseRequest(request);
			List<Integer> nums = new ArrayList<Integer>();
			for (int i = 0; i < items.size(); i++) {
				if (!items.get(i).isFormField()
						&& items.get(i).getName().length() > 0)
					nums.add(i);
				else if (items.get(i).getString() != null) // 写入参数到线程池中
					if (UploadContext.containParameter(items.get(i)
							.getFieldName()))
						UploadContext.pubParameter(
								items.get(i).getFieldName(),
								UploadContext.getParameter(items.get(i)
										.getFieldName())
										+ "@LSEAM-FGF@"
										+ items.get(i).getString(
												UploadConfigCache.encoding));
					else
						UploadContext.pubParameter(
								items.get(i).getFieldName(),
								items.get(i).getString(
										UploadConfigCache.encoding));
			}
			result.setFileNum(nums.size());
			for (Integer num : nums) {
				FileItem item = items.get(num);
				if (this.fileType.length() > 0
						&& this.fileType.toLowerCase().indexOf(
								"."
										+ getExtensionName(item.getName())
												.toLowerCase()) < 0)
					continue;
				String uploadFileName = UUID.randomUUID().toString() + "."
						+ getExtensionName(item.getName());
				item.write(new File(request.getSession().getServletContext()
						.getRealPath(uploadPath), uploadFileName));
				Thread.sleep(500);
				result.addFileList(new UploadFile(getFileName(item.getName()),
						uploadFileName, uploadPath, item.getSize()));
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.setSuccess(result.getFileNum() == result.getFileList().size());
		return result;
	}

	/**
	 * 初始化创建上传文件夹和临时文件夹
	 */
	private void init() {
		File uploadDir = new File(request.getSession().getServletContext()
				.getRealPath(uploadPath));
		File uploadTempDir = new File(request.getSession().getServletContext()
				.getRealPath(UploadConfigCache.uploadTempPath));
		if (!uploadDir.exists())
			uploadDir.mkdir();
		if (!uploadTempDir.exists())
			uploadTempDir.mkdir();
	}

	/**
	 * 获取文件名
	 */
	private String getFileName(String filePath) {
		return filePath.lastIndexOf(File.separator) > 0 ? filePath
				.substring(filePath.lastIndexOf(File.separator) + 1) : filePath;
	}

	/**
	 * 获取扩展名
	 */
	private String getExtensionName(String filePath) {
		return filePath.lastIndexOf(".") > 0 ? filePath.substring(filePath
				.lastIndexOf(".") + 1) : filePath;
	}
}